source("functions.R")

Kegg_module_UI<-function(id)
{
  ns<-NS(id)
  tagList(
     bscols(widths = 10,div(style="height: 15px;",width = '200px')),
     a("Click to be directed to KEGG organism database", href="http://www.genome.jp/kegg/catalog/org_list.html", target="_blank"),
     bscols(widths = 10,div(style="height: 15px;",width = '200px')), 
    fluidRow(column(10,DT::dataTableOutput(ns("Enriched_kegg")))),
    br(),
    hr(),
    br(),
    fluidRow(
      column(1,
             selectInput(ns("datachoice9")  ,label = h5("Select Data Type"), 
                         choices = list("Excel" = 1, "CSV" = 2),
                         selected = 1)),
      column(1, 
             br(),
             br(),
             downloadButton(ns('download_Enriched_Kegg_Table'), 'Download Enriched Kegg Table'))),
   # downloadButton(ns('download_Enriched_Kegg_Table'), 'Download full Data'),
    DT::dataTableOutput(ns("filtered_Kegg")),
   br(),
   br(),
   hr(),
   br(),
    uiOutput(ns("plot_category")),
   br(),
    fluidRow(column(12,

                    downloadButton(ns('download_kegg_plot'), 'Download Plot'),
                    plotOutput(ns("kegg"))),
    
    #          
             column(8,
                    uiOutput(ns("op")),
                    uiOutput(ns("op_an")),
                    uiOutput(ns("limit_fc")),
                    downloadButton(ns('download_kegg'), 'Download Plot'),
                    plotOutput(ns("image2"))
              ))
  )
}

Kegg_module<-function(input,output,session,DE_genes,
                      organism,dds.fc,combination,wgcna_output,anova_table)
{
  #combination()
  combo<-combination()
  print(combo())
  num<-length(combo())
  #num<-length(input$combination)
  #Compute the KEGG pathway based on a list for a list of DE genes(Uses function enrichKEGG from clusterprofiler)
  #Construct  a matrix where row->comparison A vs B, C vs D .etc
  # columns (up regulated pathways, down regulated pathways)
  #Loop through a similar matrix generated by reactive DE_genes)
  #Filter KEGG pathways for each element in the matrix generated by reactive DE_genes
  print("inside kegg line 39")
  print(organism())
  result_de<-DE_genes()
  Enriched_Kegg<-reactive({
    num<-length(combo())
    if(!is.null(wgcna_output()))
    {
      if((length(wgcna_output()$modules())>0))
      {
        enrichment_main("kegg",result_de(),organism(),dds.fc(),
                    num,wgcna_output()$modules(),wgcna_output()$WGCNA_matrix(),NULL)
      }
    }
    else
    {
      print("inside kegg line 53")
      #print(head(result()))
      print(combination())
      print(unlist(combination()))
      combo<-combination()
      print(combo())
      num<-length(combo())
      print(combo())
      print(num)
      enrichment_main("kegg",result_de(),organism(),dds.fc(),
                      num,NULL,NULL,NULL)
    }
    
  })
  
  #Display summary of KEGG pathways identified for the comparisons
  output$Enriched_kegg <- DT::renderDataTable({
    
      result<-Enriched_Kegg()[[1]]
      print(head(result))
      # num <- length(combo())
      rows<-num
      modules<-NULL
      WGCNA_matrix<-NULL
      res<-NULL#data.frame(matrix(NA, nrow = num, ncol = 3))
      
      if(!is.null(wgcna_output()))
      {
        if((length(wgcna_output()$modules())>0))
        {
          mod<-wgcna_output()$modules()
          modules<-as.data.frame(table(mod))
          colnames(modules)<-c("Var1","numbers")
          entry<-c(as.vector(combo()), as.vector(modules$Var1))
          # print(modules$Var1)
          print(entry)
          rows<-length(entry)
          
          res<-data.frame(matrix(NA, nrow = rows, ncol = 3))
          colnames(res)<-c('Up regulated','Down regulated','Regulated')
          
          
          print(modules$Var1)
        
          #print(entry)
          rownames(res)<-lapply(1:rows, function(i) {
            entry[[i]]
            
          })
          #num<-length(combo())
          for(i in 1:length(combo()))
          {
            #print(nrow(as.data.frame(result[[i]][1])))
            res[i,1]<-nrow(as.data.frame(result[[i]][[1]]))
            res[i,2]<-nrow(as.data.frame(result[[i]][[2]]))
            res[i,3]<-0
          }
          
          for(i in 1+length(combo()):nrow(modules))
          {
            #print(nrow(as.data.frame(result[[i]][1])))
            print('res')
            print(result[[i]][[3]])
            res[i,1:2]<-0
            res[i,3]<-nrow(as.data.frame(result[[i]][3]))
            
          }
        }
      }
      else{
        #num <- length(combination())
        # combo()<-combination()
        # num <-length(combination())
        res<-data.frame(matrix(NA, nrow = length(combo()), ncol = 2))
        #print(combination())
        rownames(res)<-lapply(1:length(combo()), function(i) {
         # print(combination)
          print(num)
          print(combo())
          print(length(combo()))
          # if(num==1) combo()[[1]]
          combo()[[i]]
          #paste(combination()[[i]][1],' vs ',combination()[[i]][2])
          
        })
        colnames(res)<-c('Enriched Kegg pathways for Up-reg genes','Enriched Kegg pathways for Down-reg genes')
        #print(res)
        #print(res[1,1])
        for(i in 1:length(combo()))
        {
          print(nrow(as.data.frame(result[[i]][[1]])))
          res[i,1]<-nrow(as.data.frame(result[[i]][[1]]))
          res[i,2]<-nrow(as.data.frame(result[[i]][[2]]))
        }
      }
      #print(res)
      DT::datatable(res,class = 'cell-border stripe',
                    selection = list(mode='single',target = 'cell'),
                    extensions = list('Scroller'=NULL,'Buttons'=NULL),
                    options = list(deferRender = TRUE,scrollX = TRUE,scrollY = 150,scroller = TRUE,dom = 'Bfrtip',
                                   buttons = list('copy')),#I('colvis')
                    
                    escape = FALSE
      )
    
  })

  #Display kegg pathway for the selected comparison
  
observeEvent(input$Enriched_kegg_cell_clicked,{
    print('hey')
    print(input$Enriched_kegg_cells_selected)
    print(input$Enriched_kegg_cell_clicked)
    selected <- input$Enriched_kegg_cells_selected
    row<-selected[1]
    print('row')
    print(row)
    col<-selected[2]
    print('col')
    print(col)
    
    if(length(selected)>0){
      
      output$filtered_Kegg <- DT::renderDataTable({
        print('hey')
        result<-Enriched_Kegg()[[1]]
        df<-as.data.frame(result[[row]][[col]])
        print(head(df))
        
        DT::datatable(df,class = 'cell-border stripe',
                      selection = list(mode='single',target = 'row'),
                      extensions = list('Scroller'=NULL,'Buttons'=NULL),
                      options = list(deferRender = TRUE,scrollX = TRUE,scrollY = 150,scroller = TRUE,dom = 'Bfrtip',
                                     buttons = list('copy')))
        
        
        
      })
      
      #Input to display selected kegg pathway
      output$op<-renderUI({
        if(row<=num)#input$go_wgcna>0 &&
        {
          radioButtons(session$ns("de"), "Choice of genes to be colored", choices = c("ANOVA", "DE"))
        }
        
      })
    output$op_an<-renderUI({
      combo<-combination()
      num<-length(combo())
        if(row>num)
        {
          
          if(!is.null(combo()))
          {
            print("line 216 inside kegg module")
            print(num)
            comb<-lapply(1:num, function(i) {
              combo()[[i]]
              #paste(combination()[[i]][1],' vs ',combination()[[i]][2])
              
            })
            
            checklist<-list()
            for (i in seq_along(comb)) {
              checklist[[comb[[i]]]] = i
            }
            selectInput(session$ns("ANOVA_choice"),label = h5("Choose comparison") ,
                        choices = checklist,selected = 1)
          }
        }
        
      })
      
      #Display kegg pathway plot for the pathway selected  
   observeEvent(input$filtered_Kegg_rows_selected,{
        
        print('hey_kegg')
        sel <- input$filtered_Kegg_rows_selected
        result<-Enriched_Kegg()[[1]]
        a_tab<-anova_table()[,-c(2,3)]
        print(head(a_tab))
        temp<-8
        
        #get the organism
        species=NULL
        if(as.numeric(organism())==1)
        {
          org<-org.Hs.eg.db
          species<-"hsa"
        }
        else if (as.numeric(organism())==2)
        {
          org<-org.Mm.eg.db
          species<-"mmu"
        }
        reg <- AnnotationDbi::select(org,rownames(a_tab),"ENTREZID","SYMBOL",multiVals="first")
        print('reg')
        print(head(reg))
        idx <- match(rownames(a_tab), reg$SYMBOL)
        print('idx')
        print(head(idx))
        print(typeof(idx))
        a_tab$entrez<-reg$ENTREZID[idx]
        print(head(a_tab[idx,],3))
        print(a_tab[1,6])
        #print(head(a_tab[idx,temp]))
        #print(head(reg$ENTREZID[idx]))
        #dds.fc<-batch_design()[[1]]
        dds<-colData(dds.fc())$condition
        
        geneList<-reactive({
          genList<-NULL
          res<-Enriched_Kegg()[[3]]
          df<-as.data.frame(result[[row]][[col]])
          print("Test1")
          print(df$ID[sel])
          print("test2")
          print(input$de)
          if((row<=num)&&(input$de=="DE"))
          {
            selected <- input$Enriched_kegg_cells_selected
            row<-selected[1]
            print('row')
            print(row)
            col<-selected[2]
            genList<-res[[row]][[col]]
            
          }
          else if((row<=num)&&(input$de=="ANOVA"))
          {
            temp<-3+length(unique(dds))+1+((row-1)*6)
            print(head(reg$ENTREZID[idx]))
            print(length(reg$ENTREZID[idx]))
            print(head(a_tab[idx,temp]))
            print(length(a_tab[idx,temp]))
            idx_wo_na<-which(!is.na(reg$ENTREZID[idx]))
            print(head(idx_wo_na))
            print(head(reg$ENTREZID[idx_wo_na]))
            print(head(a_tab[idx_wo_na,temp]))
            print(typeof(a_tab[idx_wo_na,temp]))
            print(typeof(reg$ENTREZID[idx_wo_na]))
            gList<-as.data.frame(matrix(NA,nrow=length(reg$ENTREZID[idx_wo_na]),ncol=2))
            colnames(gList)<-c("entrez","foldchange")
            print(typeof(gList))
            gList$foldchange<-c(as.numeric(a_tab[idx_wo_na,temp]))
            gList$entrez<-c(as.list(reg$ENTREZID[idx_wo_na]))
            #gList<-data.frame(entrez=as.vector(reg$ENTREZID[idx_wo_na]),foldchange=as.vector(a_tab[idx_wo_na,temp]))
            print('glist')
            print(typeof(gList))
            print(gList)
            #gList<-gList[complete.cases(gList), ]
            genList<-gList$foldchange
            names(genList)<-gList$entrez
            print(max(abs(genList)))
            na.omit(genList)
            #print(gList)
          }
          else if(!is.null(as.numeric(input$ANOVA_choice))){
            i<-as.numeric(input$ANOVA_choice)
            print(i)
            temp<-3+length(unique(dds))+1+((i-1)*6)#index of foldchanges of all comparisons
            idx_wo_na<-which(!is.na(a_tab$entrez))
            print(head(idx_wo_na))
            gList<-as.data.frame(matrix(NA,nrow=length(reg$ENTREZID[idx_wo_na]),ncol=2))
            colnames(gList)<-c("entrez","foldchange")
            print(typeof(gList))
            gList$foldchange<-c(as.numeric(a_tab[idx_wo_na,temp]))
            gList$entrez<-c(as.list(reg$ENTREZID[idx_wo_na]))
            #gList<-data.frame(entrez=c(reg$ENTREZID[idx]),foldchange=c(a_tab[idx,temp]))
            print('glist')
            print(head(gList))
            #gList<-gList[complete.cases(gList), ]
            #print(gList)
            genList<-gList$foldchange
            names(genList)<-gList$entrez
            print(max(abs(genList)))
            na.omit(genList)
          }
          list(genList,df$ID[sel])
        })
        
        print("test3")
        
        #print(head(geneList))
        #get the anova table
        print("genelist")
        print(geneList())
        print("rjhfjsdhfshdfjsdfhsdjfhsdf")
        if(length(geneList()[[1]])>1 && !is.null(geneList()[[1]]))
        {
          output$limit_fc<-renderUI({
            textInput(session$ns("limit_fc"), "Enter foldchange limit", value = max(abs(geneList()[[1]])), width = NULL, placeholder = NULL)
          })
          
          print("HERE")
          output$image2 <- renderImage({
            hsa04110 <- pathview(gene.data  = geneList()[[1]],
                                 pathway.id = geneList()[[2]],#"hsa04110",
                                 species    = species,#hsa",
                                 #kegg.native = FALSE,
                                 limit      = list(gene=as.numeric(input$limit_fc), cpd=1))#max(abs(geneList()[[1]]))
            print(paste(geneList()[[2]],".pathview.png",sep = ""))
            file<-list.files(pattern=paste(geneList()[[2]],".pathview.png",sep=""), full.names=TRUE)
            print(file)
            return(list(
              src = file,
              contentType = "image/png"
              # alt = "Face"
            ))
            
            
          })
          
        }
    })  
      #download button
output$download_Enriched_Kegg_Table <- downloadHandler(
        
        filename = function() 
        {
          if(as.numeric(input$datachoice9==1)){
          #condition<-paste(combination()[[row]][1],' vs ',combination()[[row]][2])
          condition <-combo()[[row]]
          if(col==1) paste('Up regulated Kegg for ',condition,'.xlsx')
          else if(col==2) paste('Down regulated Kegg for ',condition,'.xlsx')
          else if(col==3) paste('regulated Kegg for ',condition,'.xlsx')
          }
          else {
            condition <-combo()[[row]]
            if(col==1) paste('Up regulated Kegg for ',condition,'.csv')
            else if(col==2) paste('Down regulated Kegg for ',condition,'.csv')
            else if(col==3) paste('regulated Kegg for ',condition,'.csv')
          }
        },
        content = function(file) {
          #sort by adjusted p value.
          print('heyho')
          result<-Enriched_Kegg()[[1]]
          
          df<-as.data.frame(result[[row]][[col]])
          
          nam<-"Sheet 1"
          condition <-combo()[[row]]
          condition<-str_replace_all(condition,"[^[:alnum:]]",".")
          if(col==1) nam<-paste('Up regulated Kegg for ',condition)
          else if(col==2) nam<-paste('Down regulated Kegg for ',condition)
          else if(col==3) nam<-paste('regulated Kegg for ',condition)
          #write.csv(df, file)
          
          if(as.numeric(input$datachoice9==1)){
            M <- as.matrix(df)
            wb <- createWorkbook()
            addWorksheet(wb, sheetName = "Kegg table")
            writeData(wb = wb, sheet = 1, x = M, colNames = T, rowNames = T)
            saveWorkbook(wb, file)
          # write.xlsx2(df, file, sheetName = nam,
          #             col.names = TRUE, row.names = TRUE, append = FALSE)
          }
          else {
            write.csv(df, file)
          }
          
        }
        
      )

      
output$plot_category<-renderUI({
        textInput(session$ns("category"),label = h6("Enter number of categories to display"), 
                  value = "10") 
      })
#Display barplot of top 10 kegg pathway identified for selected comparison
keggplot<-reactive({
  result<-Enriched_Kegg()[[2]] #obj
  res<-Enriched_Kegg()[[1]]
  if(nrow(res[[row]][[col]]) == 0){
    warning("No Data available for plotting")
  }
  else if(nrow(res[[row]][[1]]) == 0 && nrow(res[[row]][[2]] != 0)){
    enrichment_plot("kegg",result,res,row,1,input$category,"")
  }
  else{
    enrichment_plot("kegg",result,res,row,col,input$category,"")
  }
})

output$kegg<- renderPlot({
  keggplot()
})

output$download_kegg_plot <- downloadHandler(
  filename = function()
  {
    condition <-combo()[[row]]
    # print(input$combination)
    # print(combination)
    if(col==1) paste(input$plot_k,' of Up regulated kegg for ',condition,'.svg')
    else if(col==2) paste(input$plot_k,' of Down regulated kegg for ',condition,'.svg')
    else if(col==3) paste(input$plot_k,' of regulated kegg for ',condition,'.svg')
  },
  content = function(file) {
    #png(file)
    print(file)
    ggsave(file,keggplot())#,width=800, height=500)
    #dev.off()
  })
    }
})
return(list(
       Enriched_Kegg_table=reactive({Enriched_Kegg()[[1]]}),
       Enriched_Kegg_obj=reactive({Enriched_Kegg()[[2]]})
)
       )
}
